<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/3
 * Time: 16:45
 * 个人中心模块
 */
namespace app\home\model;

use app\home\model\Base;
use think\Model;
use think\Request;
use think\Db;
use think\Exception;
use think\Log;
use think\Session;
use wxpay\Wxpay;   // 微信支付

class Personal extends Base {

    /**
     * 构造
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取登录用户的基本信息、认证信息
     * @param int $uid 直接客户id
     * 注：数据里面的id代表资质表的id，client_id代表用户表id
     */
    public function getUserInfoM($uid = 0)
    {
        try {
            $uid = $uid ? $uid : $this->user_info['id'];   // 未登录状态下快速续费
            $client_fields = "c.`id`,c.`link_user`,c.`phone`,c.`email`,c.`address`,c.`type` AS ctype,c.`addtime`,c.`number`,c.`agent_id`,c.`role_id`,c.`appid`,c.`restkey`,c.`setpkg`,c.`isfree`,c.`setbag`,";
            $approve_fields = "a.`id` AS aid,a.`company_name`,a.`company_address`,a.`type` AS atype";
            $sql = "SELECT ".$client_fields.$approve_fields." FROM yc_client as c LEFT JOIN yc_client_approve as a on c.id = a.client_id WHERE c.id = ".$uid;
            $user_info = Db::query($sql);
            return $user_info[0];
        } catch (Exception $e) {
            Log::write('获取登陆用户信息异常：'.$e->getMessage(),'error');
        }
    }
    
    /**
     * 修改用户密码
     * 验证原密码是否正确
     */
    public function modifyPasswdM()
    {
        try {
            $param = Request::instance()->post();
            // 验证原密码
            $opasswd = $this->user_info['pass'];
            if( md5($param['opasswd']) != $this->user_info['pass'] ) {
                return ['code'=>1,'msg'=>'原密码错误'];
            }
            // 验证新密码
            $check_password = "/^\w{6,16}/";
            if(!preg_match_all($check_password,$param['passwd'])){
                return ['code'=>2,'msg'=>'密码由6-16位字母数字下划线组成'];
            }
            $md5_password = md5($param['passwd']);
            $sql = "UPDATE yc_client SET `pass` = '".$md5_password."' WHERE `id` = ".$this->user_info['id'];
            $result = Db::execute($sql);
            if( $result === false ){
                return ['code'=>3,'msg'=>'修改密码失败，请稍后尝试'];
            }
            // session数据更新
            $this->user_info['pass'] = $md5_password;
            Session::set('S_USER_INFO',$this->user_info);
            return ['code'=>0,'msg'=>'修改密码成功'];
        } catch (Exception $e) {
            Log::write('修改用户密码异常：'.$e->getMessage(),'error');
        }
    }

    /**
     * 获取我的账户余额
     * @return string $balance 账户余额
     */
    public function getMyAccountBalanceM()
    {
        try {
            $sql = "SELECT `id`,`order_number`,`pay_type`,`money`,`freight`,`addtime` FROM yc_order WHERE (payer = ".$this->user_info['id']." and payee = ".$this->user_info['agent_id']." and user_type = 3 and status in ('1','4'))";
            $sql .= " or (payer = ".$this->user_info['agent_id']." and payee = ".$this->user_info['id']." and user_type = 2 and status = 1)";
            $order = Db::query($sql);
            $balance = 0;   // 默认余额
            $pay_array = ['3','4','5','7','8','9','10','11','12'];   // 余额支出数组
            foreach($order as &$value){
                if(in_array($value['pay_type'],$pay_array)){
                    $balance -= $value['money'];
                } else {
                    $balance += $value['money'];
                }
            }
            $balance = round($balance/100,2);   // 处理余额
            return $balance;
        } catch (Exception $e) {
            Log::write('获取我的账户余额异常：'.$e->getMessage(),'error');
        }
    }

    /**
     * 获取我的账户信息，默认每页显示10条
     * @return array $order 账户信息
     */
    public function getMyAccountM()
    {
        try {
            // 获取当前页数的数据
            $where = "payer = ".$this->user_info['id']." and payee = ".$this->user_info['agent_id']." and user_type = 3 and status in ('1','4')";
            $whereOr = "payer = ".$this->user_info['agent_id']." and payee = ".$this->user_info['id']." and user_type = 2 and status = 1";
            $data = Db::name('order')
                ->field('id,order_number,pay_type,money,freight,addtime')
                ->where($where)
                ->whereOr($whereOr)
                ->order('id desc')
                ->paginate(10,false);
            $order = $data->toArray();
            $pay_array = ['3','4','5','7','8','9','10','11','12'];   // 余额支出数组
            foreach($order['data'] as &$value){
                if(in_array($value['pay_type'],$pay_array)){
                    $value['money'] = '-'.$value['money']/100;
                } else {
                    $value['money'] = '+'.$value['money']/100;
                }
                $value['pay_type_name'] = $this->pay_type[$value['pay_type']];
                $value['addtime'] = date('Y-m-d H:i:s',$value['addtime']);
            }
            return $order;
        } catch (Exception $e) {
            Log::write('获取我的账户信息异常：'.$e->getMessage(),'error');
        }
    }

    /**
     * 添加新的收货地址
     * 如果新的地址是默认地址，更新其他地址的默认状态
     */
    public function addAddressM()
    {
        try {
            $param = Request::instance()->post();
            Db::startTrans();   // 开启事务
            $param['type'] = isset($param['type']) ? 1 : 2;   // 1：默认地址
            if($param['type'] == '1'){  // 更新已添加的地址默认状态
                $sql_update = "UPDATE yc_address SET `status` = 2 WHERE `user_id`=".$this->user_info['id']." AND `user_type` = 3";
                $update = Db::execute($sql_update);
            }
            $param['regions'] = explode(',',$param['regions']);  // 省市区
            $sql_insert = "INSERT INTO yc_address (`user_id`,`user_type`,`name`,`phone`,`address`,`status`,`addtime`,`province`,`city`,`area`)";
            $sql_insert .= " VALUES (".$this->user_info['id'].",3,'".$param['consignee']."','".$param['phone']."','".$param['detailed']."',".$param['type'].",'".time()."',".$param['regions'][0].",".$param['regions'][1].",".$param['regions'][2].")";
            $insert = Db::execute($sql_insert);
            if($insert && $update !== false){
                Db::commit();
                return ['code'=>0,'msg'=>'新增地址成功'];
            } else {
                Db::rollback();
                return ['code'=>1,'msg'=>'新增地址失败'];
            }
        } catch (Exception $e){
            Log::write('新增收货地址异常：'.$e->getMessage(),'error');
        }
    }

    /**
     * 获取省市区数据，生成js文件
     */
    public function getProvincesArrM()
    {
        try {
            $file_url = $_SERVER['DOCUMENT_ROOT'].'/public/static/phone/picker/js/regions.js';
            if(file_exists($file_url)){   // 存在地区资源文件,直接返回
                return false;
            }
            $area_json = [];
            $sql = "SELECT `id`,`provinceid`,`province` FROM yc_provinces";
            $result = Db::query($sql);   // 获取省份信息
            foreach($result as $key=>$value){   // 获取省份下面的城市信息
                $sql_city = "SELECT `id`,`city`,`cityid` FROM yc_cities WHERE `provinceid` = ".$value['provinceid'];
                $city = Db::query($sql_city);
                $area_json[$key]['id'] = $value['id'];
                $area_json[$key]['name'] = $value['province'];
                $area_json[$key]['child'] = $city;
            }
            foreach($area_json as $key=>$value){
                foreach($value['child'] as $k=>$ar){
                    $sql_area = "SELECT `id`,`area` FROM yc_areas WHERE `cityid` = ".$ar['cityid'];
                    $area = Db::query($sql_area);
                    $area_json[$key]['child'][$k]['id'] = $ar['id'];
                    $area_json[$key]['child'][$k]['name'] = $ar['city'];
                    unset($area_json[$key]['child'][$k]['city']);
                    unset($area_json[$key]['child'][$k]['cityid']);
                    $area_json[$key]['child'][$k]['child'] = $area;
                }
            }
            foreach($area_json as $key=>$value){
                foreach($value['child'] as $k=>$ar){
                    foreach($ar['child'] as $a=>$r){
                        $area_json[$key]['child'][$k]['child'][$a]['id'] = $r['id'];
                        $area_json[$key]['child'][$k]['child'][$a]['name'] = $r['area'];
                        unset($area_json[$key]['child'][$k]['child'][$a]['area']);
                    }
                }
            }
            touch($file_url);   // 创建js文件
            $myfile = fopen($file_url, "w") or die("Unable to open file!");  // 初始化省市区资源文件
            $txt = 'var Regions='.json_encode($area_json);
            fwrite($myfile, $txt);
            fclose($myfile);
            return true;
        } catch (Exception $e) {
            Log::write('获取省份信息异常：'.$e->getMessage(),'error');
        }
    }

    /**
     * 获取微信JSAPI支付参数
     */
    public function getWxPayParam()
    {
        try {
            $param = Request::instance()->post();
            $openId = Session::get('S_WX_OPENID');
            if(!$openId){
                return ['code'=>1,'msg'=>'微信支付异常！'];
            }
            // 获取微信支付相关配置
//            $get_config = $this->getAdminConfig($user_type = 1, $type = 1);   // 默认获取总后台作为测试用
            $get_config = $this->getAdminConfig($user_type = 2, $type = 1, $user_id = $this->user_info['agent_id']);   // 获取直接客户对应的代理商配置
            if(!$get_config){
                return ['code'=>2,'msg'=>'微信支付异常！'];
            }
            $wx_config = $get_config[0]['data'];
            // 验证金额
            if(!preg_match("/^[1-9][0-9]*$/",$param['money'])){
                return ['code'=>3,'msg'=>'充值金额错误'];
            }
            $order_money = $param['money']*100;   // 订单金额，单位分
            $order_type = '01';   // 订单类型
            $order_source = 2;   // 订单来源 2：在线微信
            $order_info = '';   // 订单内容
            $order_status = 2;   // 订单状态
            // 生成订单
            $create_order = $this->createOrder($order_money, $order_type, $order_source, $order_info, $order_status);
            if(!$create_order){
                return ['code'=>4,'msg'=>'生成充值订单异常！'];
            }
            // 获取微信公众号支付相关的参数
            $JSAPI = array(
                'body'=>'物联网卡平台充值',  // 商品名称
                'out_trade_no'=>$create_order.mt_rand(1000,9999),  // 订单号+4位随机数
                'total_fee'=>$order_money,
                'spbill_create_ip'=>Request::instance()->ip(),   // 终端ip
                'NotifyUrl'=>"http://".$_SERVER['HTTP_HOST']."/home/Quick/wxNotifyUrl",
                'openid'=>$openId,
            );
            // 调用微信JSAPI支付，获取相关信息
            vendor('wxpay.Wxpay');
            $wx_pay = new \wxpay\Wxpay($wx_config['app_id'],$wx_config['mch_id'],$wx_config['appsecret'],$wx_config['mch_key']);
            $pay_conf = $wx_pay->GetPrePayMsg($JSAPI);
            if(!$pay_conf){
                return ['code'=>5,'msg'=>'支付异常！'];
            }
            return ['code'=>0,'msg'=>$pay_conf];
        } catch (Exception $e) {
            Log::write('获取JSAPI支付参数异常：'.$e->getMessage(),'error');
        }
    }
    
}